﻿using UnityEngine;
using UnityEditor;

public class RemoveMissingScripts : EditorWindow
{
    [MenuItem("Tools/Remove Missing Scripts in Current Scene")]
    public static void RemoveScriptsInCurrentScene()
    {
        int missingCount = 0;

        // 获取当前场景中的所有游戏对象
        GameObject[] allGameObjects = GameObject.FindObjectsOfType<GameObject>();

        foreach (GameObject go in allGameObjects)
        {
            Component[] components = go.GetComponents<Component>();
            SerializedObject so = new SerializedObject(go);
            SerializedProperty property = so.FindProperty("m_Component");

            int r = 0;
            for (int j = 0; j < components.Length; j++)
            {
                if (components[j] == null)
                {
                    property.DeleteArrayElementAtIndex(j - r);
                    r++;
                    missingCount++;
                }
            }

            so.ApplyModifiedProperties();
        }

        Debug.Log($"Removed {missingCount} missing scripts in the current scene.");
    }

    [MenuItem("Tools/Remove Missing Scripts in Selected Objects")]
    public static void RemoveScriptsInSelectedObjects()
    {
        int missingCount = 0;

        foreach (GameObject go in Selection.gameObjects)
        {
            Component[] components = go.GetComponents<Component>();
            SerializedObject so = new SerializedObject(go);
            SerializedProperty property = so.FindProperty("m_Component");

            int r = 0;
            for (int j = 0; j < components.Length; j++)
            {
                if (components[j] == null)
                {
                    property.DeleteArrayElementAtIndex(j - r);
                    r++;
                    missingCount++;
                }
            }

            so.ApplyModifiedProperties();
        }

        Debug.Log($"Removed {missingCount} missing scripts in selected objects.");
    }
}